<template>
  <div>
    <el-upload
      :action="uploadUrl"
      :headers="headers"
      :limit="1"
      :before-upload="file => {return beforeUpload(file)}"
      :on-success="handleUploadSuccess"
      list-type="picture-card"
      :file-list="fileList"
    >
      <i slot="default" class="el-icon-plus" />
      <div slot="file" slot-scope="{file}" class="img-file">
        <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
        <span class="el-upload-list__item-actions">
          <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
            <i class="el-icon-zoom-in" />
          </span>
          <span class="el-upload-list__item-delete" @click="handleDownload(file)">
            <i class="el-icon-download" />
          </span>
          <span class="el-upload-list__item-delete" @click="handleRemove(file)">
            <i class="el-icon-delete" />
          </span>
        </span>
      </div>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible" custom-class="aaa" :append-to-body="true">
      <img :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>

</template>

<script>
import download from 'downloadjs'
import { removeObject } from '@/api/oss/oss'
import { getToken } from '@/utils/auth'

export default {
  name: 'UploadImg',
  props: {
    name: String,
    url: String,
    limitSize: Number,
    fileList: Array
  },
  data() {
    return {
      dialogVisible: false,
      dialogImageUrl: true,
      // 设置上传的请求头部
      headers: { Authorization: 'Bearer ' + getToken() },
      // 上传的地址
      uploadUrl: process.env.VUE_APP_BASE_API + `/file/oss/uploadObject?bucketName=${process.env.VUE_APP_DOWNLOAD_URL}&genRandomKey=true`
    }
  },
  methods: {
    /**
     * 文件验证
     * @param file 文件
     * @returns {boolean} 结果
     */
    beforeUpload(file) {
      if (file.type.indexOf('image/') === -1) {
        this.$modal.msgError('文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。')
        return false
      }
      if (file.size > this.limitSize * 1024) {
        this.$modal.msgError(`文件大小不能超过${this.limitSize}KB`)
        return false
      }
      return true
    },
    handleUploadSuccess(res, file, fileList) {
      this.$emit('updateConfig', `${this.name}Url`, res.data)
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleDownload(file) {
      download(file.url)
    },
    handleRemove(file) {
      this.$emit('updateFileList', `${this.name}FileList`, file)
      removeObject({
        bucketName: process.env.VUE_APP_DOWNLOAD_URL,
        objectName: this.url
      }).then(res => {
        this.$emit('updateConfig', `${this.name}Url`, null)
      }).catch(err => {
        console.error(err)
        this.$message.error('图片删除失败')
      })
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__body {
  text-align: center;
}
img {
  max-width: 100%;
  object-fit: scale-down;
}
</style>
